<template>
  <view>
    <!-- 原有按钮 -->
    <button @tap="handleBack">返回</button>
   
    <!-- 新增档案管理区域 -->
    <view class="archive-section">
      <!-- 自我简介编辑 -->
      <view class="archive-item">
        <text class="item-title">自我介绍</text>
        <textarea v-model="profile.introduction" 
                  placeholder="请输入您的专业背景和服务优势..." 
                  class="intro-input"/>
        <button @tap="saveIntroduction" size="mini">保存简介</button>
      </view>
      
      <!-- 营业执照上传 -->
      <view class="archive-item">
        <text class="item-title">营业执照</text>
        <image v-if="profile.businessLicense" 
               :src="profile.businessLicense" 
               class="license-img"
               @tap="previewImage(profile.businessLicense)"></image>
        <button @tap="uploadFile('businessLicense')" size="mini">
          {{ profile.businessLicense ? '更新' : '上传' }}
        </button>
      </view>
      
      <!-- 年检报告上传 -->
      <view class="archive-item">
        <text class="item-title">年检报告</text>
        <image v-if="profile.annualReport" 
               :src="profile.annualReport" 
               class="license-img"
               @tap="previewImage(profile.annualReport)"></image>
        <button @tap="uploadFile('annualReport')" size="mini">
          {{ profile.annualReport ? '更新' : '上传' }}
        </button>
      </view>
    </view>
	<button @tap="handleLogout" type="warn">退出登录</button>
	
  </view>
</template>

<script setup>
	
	import { onLoad } from "@dcloudio/uni-app"
	import { ref,onMounted } from "vue"
	
	// 用户档案数据
	const profile = ref({
	  introduction: '',
	  businessLicense: '',
	  annualReport: ''
	})
	
	// 页面加载时获取档案数据
	onLoad(async (options) => {
	  await fetchUserProfile()
	})
	
	// 获取用户档案
	const fetchUserProfile = async () => {
	  try {
	    const token = uni.getStorageSync('token')
	    const res = await uni.request({
	      url: 'https://your-api-domain.com/user/profile',
	      method: 'GET',
	      header: { 'Authorization': `Bearer ${token}` }
	    })
	    
	    if (res.data.code === 200) {
	      profile.value = {
	        ...profile.value,
	        ...res.data.data
	      }
	    }
	  } catch (e) {
	    console.error('档案获取失败', e)
	  }
	}
	
	// 保存自我介绍
	const saveIntroduction = async () => {
	  try {
	    const token = uni.getStorageSync('token')
	    const res = await uni.request({
	      url: 'https://your-api-domain.com/user/profile',
	      method: 'POST',
	      header: { 
	        'content-type': 'application/json',
	        'Authorization': `Bearer ${token}`
	      },
	      data: { introduction: profile.value.introduction }
	    })
	    
	    if (res.data.code === 200) {
	      uni.showToast({ title: '简介更新成功', icon: 'success' })
	    }
	  } catch (e) {
	    uni.showToast({ title: '保存失败', icon: 'none' })
	  }
	}
	
	// 文件上传[6,9](@ref)
	const uploadFile = (type) => {
	  uni.chooseImage({
	    count: 1,
	    sizeType: ['compressed'], // 压缩图片
	    success: async (res) => {
	      const filePath = res.tempFilePaths[0]
	      uni.showLoading({ title: '上传中...', mask: true })
	      
	      try {
	        const token = uni.getStorageSync('token')
	        const uploadRes = await uni.uploadFile({
	          url: 'http://115.190.38.218/go/api/v1/upload',
	          filePath: filePath,
	          name: 'file',
	          formData: { fileType: type },
	          header: { 'Authorization': `Bearer ${token}` }
	        })
	        
	        const data = JSON.parse(uploadRes.data)
	        if (data.code === 200) {
	          profile.value[type] = data.url
	          uni.showToast({ title: '上传成功', icon: 'success' })
	        }
	      } catch (e) {
	        uni.showToast({ title: '上传失败', icon: 'none' })
	      } finally {
	        uni.hideLoading()
	      }
	    }
	  })
	}
	
	// 图片预览[11](@ref)
	const previewImage = (url) => {
	  uni.previewImage({
	    urls: [url],
	    current: 0
	  })
	}
	
	// 返回处理
	const handleBack = () => {
		// 判断是否有上一页可返回
		const pages = getCurrentPages()
		if(pages.length > 1) {
			uni.navigateBack({
				delta: 1,
				fail: (err) => {
					console.error("返回失败:", err)
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			})
		} else {
			// 如果没有上一页，默认跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	}
	
	// 退出登录处理
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					// 清除本地存储的token和用户信息
					uni.removeStorageSync('token')
					uni.removeStorageSync('info')
					uni.removeStorageSync("type")
					console.log("已退出登录")
					
					// 跳转到登录页，使用reLaunch关闭所有页面
					uni.reLaunch({
						url: '/pages/login/login',
						success: () => {
							uni.showToast({
								title: '退出成功',
								icon: 'success'
							})
						},
						fail: (err) => {
							console.error("跳转失败:", err)
						}
					})
				}
			}
		})
	}
</script>

<style scoped>
	button {
		margin: 30rpx;
	}
	
	/* 退出按钮特殊样式 */
	button[type="warn"] {
		background-color: #ff5a5f;
		color: white;
	}
	
	
	/* 新增档案样式 */
	.archive-section {
	  margin: 40rpx;
	  padding: 30rpx;
	  background: #fff;
	  border-radius: 16rpx;
	  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	}
	
	.archive-item {
	  margin-bottom: 50rpx;
	  padding-bottom: 40rpx;
	  border-bottom: 1rpx solid #eee;
	}
	
	.item-title {
	  font-weight: bold;
	  display: block;
	  margin-bottom: 20rpx;
	  font-size: 32rpx;
	}
	
	.intro-input {
	  width: 100%;
	  height: 200rpx;
	  padding: 20rpx;
	  border: 1rpx solid #ddd;
	  border-radius: 8rpx;
	  margin-bottom: 20rpx;
	  font-size: 28rpx;
	}
	
	.license-img {
	  width: 300rpx;
	  height: 200rpx;
	  border: 1rpx dashed #ddd;
	  margin: 20rpx 0;
	  border-radius: 8rpx;
	}
</style>